const express = require('express')
const router = express.Router()
const houseService = require('services/house')
const orderService = require('services/order')
const Payment = require('wechat-pay').Payment
const config = require('config')
const moment = require('moment')
const paymentConfig = require('../paymentConfig')
const payment = new Payment(paymentConfig);

async function payArgsByOrder (order, house, user) {
  const paymentOrder = {
    body:  `${house.name} ${moment(order.startTime).format('YYYY-MM-DD HH:mm')} - ${moment(order.endTime).format('YYYY-MM-DD HH:mm')}`,
    attach: '',
    out_trade_no: config.env + '_' + order.id,
    total_fee: order.orderPrice * 100,
    spbill_create_ip: '127.0.0.1',
    openid: user.wechatOpenId,
    trade_type: 'JSAPI'
  }
  let payargs = await payment.getBrandWCPayRequestParams(paymentOrder)
  let prepayId = payargs.package.split('=')[1]
  await orderService.setPrepayId(order.id, prepayId)
  payargs.orderId = order.id
  return payargs
}

router.post('/:id/paymentParams', async (req, res, next) => {
  const orderId = req.params.id
  const order = await orderService.get(orderId)
  if (order.userId !== req.user.id) {
    return next('Invalid user')
  }
  try {
    let payargs = await payArgsByOrder(order, order.house, req.user)
    res.json(payargs)
  } catch (e) {
    if (e.name !== 'Error') {
      return next(new BizError(e.message))
    } else {
      return next(e)
    }
  }
})

router.post('/paymentParams', async (req, res, next) => {
  try {
    const orderData = req.body
    const house = await houseService.get(orderData.houseId)
    orderData.userId = req.user.id
    orderData.startTime = new Date(orderData.startTime)
    orderData.endTime = new Date(orderData.endTime)
    const { openTime, closeTime } = house
    const { startTime, houseId, count, endTime, periodType } = orderData
    if (orderData.startTime < new Date()) {
      throw new BizError('当前时段已过期')
    }

    if (periodType == 4 && !moment(endTime).isSame(startTime, 'day')) {
      throw new BizError('分时预订暂不支持跨日')
    }

    if (periodType == 4) {
      if (startTime && endTime && startTime.getHours() < openTime && endTime.getHours() > closeTime) {
        throw new BizError('超出营业时段，不可预订')
      }
      if (await orderService.checkPeriodHasOrder(houseId, startTime, endTime)) {
        throw new BizError('该时段不可预订')
      }
    }

    if (periodType == 3) {
      if (await orderService.checkPeriodHasOrder(houseId, startTime, endTime)) {
        throw new BizError('该日期不可预订')
      }
    }

    const order = await orderService.create(orderData)

    // 更新日期是否可预订
    if (periodType == 3) {
      for (let i = 0; i < count; i++) {
        await orderService.updateDateStatus(houseId, new Date(+startTime + i * 3600 * 24 * 1000))
      }
    } else if (periodType == 4) {
      const availableHours = startTime && endTime ? (endTime.getHours() - startTime.getHours()) : 24
      const orders = await orderService.getOrdersByDate(houseId, startTime)
      const hours = orders.map(order => order.count).reduce((a, b) => {
        return a + b
      }, 0)
      if (hours == availableHours) {
        await orderService.updateDateStatus(houseId, startTime)        
      }
    }

    let payargs = await payArgsByOrder(order, house, req.user)
    res.json(payargs)
  } catch (e) {
    // console.log('e', e.message)
    next(e)
  }
})

router.get('/', async (req, res, next) => {
  res.send([])
})

router.get('/:id', async (req, res, next) => {
  const order = await orderService.get(req.params.id)
  if (!order) {
    res.status(404).send({'message': 'order not exists'})
    return
  }
  res.send(order)
})

module.exports = router